//go:build !no_docker_sock_check
// +build !no_docker_sock_check

/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package escaping

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/errors"
	"github.com/cdk-team/CDK/pkg/exploit/base"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/util"
)

// APIs Ref https://github.com/AbsoZed/DockerPwn.py/blob/master/createContainer.py
// curl --unix-socket /var/run/docker.sock http://127.0.0.1/info
func CheckDockerSock(path string) error {
	_, err := os.Stat(path)
	if err != nil {
		return &errors.CDKRuntimeError{Err: err, CustomMsg: "err found while stat docker.sock path."}
	}
	body, err := util.UnixHttpSend("get", path, "http://127.0.0.1/info", "")
	if err != nil {
		return &errors.CDKRuntimeError{Err: err, CustomMsg: "failed to send http request to unix socket."}
	}
	fmt.Println("\t" + body)
	if strings.Contains(body, "Containers") {
		log.Println("success, docker.sock is available. please use `./cdk ucurl` commands to control docker API")
		log.Println("you can find Docker APIs in https://docs.docker.com/engine/api/v1.24/")
		log.Println("happy escaping!")
	} else {
		log.Println("cannot get docker daemon info from target unix socket.")
	}
	return nil
}

// plugin interface
type DINDAttackS struct{ base.BaseExploit }

func (p DINDAttackS) Desc() string {
	return "check if docker unix socket available. usage: ./cdk run docker-sock-check <sock_path>"
}
func (p DINDAttackS) Run() bool {
	args := cli.Args["<args>"].([]string)
	if len(args) != 1 {
		log.Println("invalid input args.")
		log.Fatal(p.Desc())
	}

	sock := args[0]
	log.Println("checking docker socket: ", sock)

	err := CheckDockerSock(sock)
	if err != nil {
		log.Println(err)
		return false
	} else {
		return true
	}
}

func init() {
	exploit := DINDAttackS{}
	exploit.ExploitType = "escaping"
	plugin.RegisterExploit("docker-sock-check", exploit)
}
